package com.thiswhyme.sentinel.server.instance2.config;

import com.alibaba.csp.sentinel.cluster.ClusterStateManager;
import com.alibaba.csp.sentinel.cluster.client.config.ClusterClientAssignConfig;
import com.alibaba.csp.sentinel.cluster.client.config.ClusterClientConfig;
import com.alibaba.csp.sentinel.cluster.client.config.ClusterClientConfigManager;
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource;
import com.alibaba.csp.sentinel.init.InitFunc;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.PropertyKeyConst;

import java.util.Properties;

/**
 * 简单版本
 * @author Eric Zhao
 */
public class ClusterClientInitFunc implements InitFunc {

    private final String remoteAddress = "127.0.0.1:8848";
    private final String nacosNamespace = "b58f5675-6f17-47d0-b173-3bf416141ea0";
    private final String groupId = "sentinel";
    private final String configDataId = "sentinel-token-server-config";

    @Override
    public void init() throws Exception {
        initClientServerAssignProperty();
        ClusterStateManager.applyState(ClusterStateManager.CLUSTER_CLIENT);
    }

    /**
     * 指定token-server，请求配置超时时间
     */
    private void initClientServerAssignProperty() {
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, remoteAddress);
        properties.put(PropertyKeyConst.NAMESPACE, nacosNamespace);

        // client端加载requestTimeout配置
        ReadableDataSource<String, ClusterClientConfig> clientConfigDs = new NacosDataSource<>(properties, groupId,
                configDataId, source -> JSON.parseObject(source, ClusterClientConfig.class));
        ClusterClientConfigManager.registerClientConfigProperty(clientConfigDs.getProperty());

        // 设置token-server
        ReadableDataSource<String, ClusterClientAssignConfig> clientAssignDs = new NacosDataSource<>(properties, groupId,
                configDataId, source -> JSON.parseObject(source, ClusterClientAssignConfig.class));
        ClusterClientConfigManager.registerServerAssignProperty(clientAssignDs.getProperty());
    }
}
